#include "connectdialog.h"
#include <QLineEdit>
#include <QComboBox>
#include <QPushButton>
#include <QCheckBox>
#include <QSpinBox>
#include <QLabel>
#include <QFormLayout>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>
#include <QRegularExpressionValidator>

ConnectDialog::ConnectDialog(QWidget *parent)
    : QDialog(parent)
{
    setupUI();
    loadSettings();
    validateInput();
    
    setWindowTitle(tr("连接到远程桌面"));
    setMinimumWidth(400);
}

ConnectDialog::~ConnectDialog()
{
}

QString ConnectDialog::getHost() const
{
    return hostLineEdit->text().trimmed();
}

int ConnectDialog::getPort() const
{
    return portSpinBox->value();
}

QString ConnectDialog::getUsername() const
{
    return usernameLineEdit->text().trimmed();
}

QString ConnectDialog::getPassword() const
{
    return passwordLineEdit->text();
}

QString ConnectDialog::getDomain() const
{
    return domainLineEdit->text().trimmed();
}

QString ConnectDialog::getProtocol() const
{
    return protocolComboBox->currentText();
}

void ConnectDialog::browseKeyFile()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("选择密钥文件"), 
                                                    QDir::homePath(), 
                                                    tr("密钥文件 (*.key)"));
    if (!fileName.isEmpty()) {
        keyFileLineEdit->setText(fileName);
    }
}

void ConnectDialog::testConnection()
{
    QMessageBox::information(this, tr("测试连接"), 
                             tr("连接测试功能将在完整实现中提供"));
}

void ConnectDialog::accept()
{
    saveSettings();
    QDialog::accept();
}

void ConnectDialog::reject()
{
    saveSettings();
    QDialog::reject();
}

void ConnectDialog::protocolChanged(int index)
{
    Q_UNUSED(index)
    // 根据协议类型更新UI
    QString protocol = protocolComboBox->currentText();
    
    if (protocol == "VNC") {
        // VNC不需要域
        domainLineEdit->setEnabled(false);
        portSpinBox->setValue(5900);
    } else if (protocol == "RDP") {
        // RDP需要域
        domainLineEdit->setEnabled(true);
        portSpinBox->setValue(3389);
    }
}

void ConnectDialog::setupUI()
{
    // 主机地址
    hostLineEdit = new QLineEdit("127.0.0.1");
    hostLineEdit->setPlaceholderText(tr("输入主机地址"));
    
    // 端口
    portSpinBox = new QSpinBox;
    portSpinBox->setRange(1, 65535);
    portSpinBox->setValue(5900);
    
    // 协议选择
    protocolComboBox = new QComboBox;
    protocolComboBox->addItem("VNC");
    protocolComboBox->addItem("RDP");
    connect(protocolComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &ConnectDialog::protocolChanged);
    
    // 用户名
    usernameLineEdit = new QLineEdit;
    usernameLineEdit->setPlaceholderText(tr("输入用户名"));
    
    // 密码
    passwordLineEdit = new QLineEdit;
    passwordLineEdit->setEchoMode(QLineEdit::Password);
    passwordLineEdit->setPlaceholderText(tr("输入密码"));
    
    // 域（RDP）
    domainLineEdit = new QLineEdit;
    domainLineEdit->setPlaceholderText(tr("输入域"));
    domainLineEdit->setEnabled(false);
    
    // 密钥文件
    keyFileLineEdit = new QLineEdit;
    keyFileLineEdit->setPlaceholderText(tr("可选的密钥文件路径"));
    browseButton = new QPushButton(tr("浏览..."));
    connect(browseButton, &QPushButton::clicked, this, &ConnectDialog::browseKeyFile);
    
    // 记住密码
    rememberPasswordCheckBox = new QCheckBox(tr("记住密码"));
    
    // 按钮
    testButton = new QPushButton(tr("测试连接"));
    connect(testButton, &QPushButton::clicked, this, &ConnectDialog::testConnection);
    
    connectButton = new QPushButton(tr("连接"));
    connectButton->setDefault(true);
    connect(connectButton, &QPushButton::clicked, this, &ConnectDialog::accept);
    
    cancelButton = new QPushButton(tr("取消"));
    connect(cancelButton, &QPushButton::clicked, this, &ConnectDialog::reject);
    
    // 布局
    formLayout = new QFormLayout;
    formLayout->addRow(tr("主机地址:"), hostLineEdit);
    formLayout->addRow(tr("端口:"), portSpinBox);
    formLayout->addRow(tr("协议:"), protocolComboBox);
    formLayout->addRow(tr("用户名:"), usernameLineEdit);
    formLayout->addRow(tr("密码:"), passwordLineEdit);
    formLayout->addRow(tr("域:"), domainLineEdit);
    
    // 认证信息组
    authGroupBox = new QGroupBox(tr("认证信息"));
    authGroupBox->setLayout(formLayout);
    
    // 按钮布局
    buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(testButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(connectButton);
    buttonLayout->addWidget(cancelButton);
    
    // 主布局
    mainLayout = new QVBoxLayout;
    mainLayout->addWidget(authGroupBox);
    mainLayout->addLayout(buttonLayout);
    setLayout(mainLayout);
    
    // 连接输入验证
    connect(hostLineEdit, &QLineEdit::textChanged, this, &ConnectDialog::validateInput);
    connect(usernameLineEdit, &QLineEdit::textChanged, this, &ConnectDialog::validateInput);
}

void ConnectDialog::loadSettings()
{
    QSettings settings;
    
    hostLineEdit->setText(settings.value("connectdialog/host", "127.0.0.1").toString());
    portSpinBox->setValue(settings.value("connectdialog/port", 5900).toInt());
    usernameLineEdit->setText(settings.value("connectdialog/username").toString());
    rememberPasswordCheckBox->setChecked(settings.value("connectdialog/rememberPassword", false).toBool());
    
    if (rememberPasswordCheckBox->isChecked()) {
        passwordLineEdit->setText(settings.value("connectdialog/password").toString());
    }
    
    int protocolIndex = settings.value("connectdialog/protocol", 0).toInt();
    protocolComboBox->setCurrentIndex(protocolIndex);
    protocolChanged(protocolIndex);
}

void ConnectDialog::saveSettings()
{
    QSettings settings;
    
    settings.setValue("connectdialog/host", hostLineEdit->text());
    settings.setValue("connectdialog/port", portSpinBox->value());
    settings.setValue("connectdialog/username", usernameLineEdit->text());
    settings.setValue("connectdialog/protocol", protocolComboBox->currentIndex());
    settings.setValue("connectdialog/rememberPassword", rememberPasswordCheckBox->isChecked());
    
    if (rememberPasswordCheckBox->isChecked()) {
        settings.setValue("connectdialog/password", passwordLineEdit->text());
    } else {
        settings.remove("connectdialog/password");
    }
}

void ConnectDialog::validateInput()
{
    bool valid = !hostLineEdit->text().trimmed().isEmpty() && 
                 !usernameLineEdit->text().trimmed().isEmpty();
    connectButton->setEnabled(valid);
}